/*
 * Project: book
 * 
 * File Created at 2017年9月7日
 * 
 * Copyright 2016 CMCC Corporation Limited.
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of
 * ZYHY Company. ("Confidential Information").  You shall not
 * disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license.
 */
package com.whb.book.service.Impl;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.whb.book.common.redis.RedisUtil;
import com.whb.book.dao.BookDao;
import com.whb.book.dto.SyncUserVO;
import com.whb.book.entity.Book;
import com.whb.book.service.BookService;

/**
 * @Type BookServiceImpl.java
 * @Desc 
 * @author wanghb
 * @date 2017年9月7日 下午10:59:04
 * @version 
 */
@Service
public class BookServiceImpl implements BookService {

    @Autowired
    private BookDao bookDao;

    @Autowired
    private RedisUtil redisUtil;

    private static String SPILIT = "#";
    private static String ID = "id";
    private static int EXPIRE_TIME = 3600;//seconds
    private static String BOOK_KEY = Book.class.getName();

    private String idKey(Long id, String type) {
        StringBuilder sb = new StringBuilder();
        sb.append(type).append(SPILIT).append(ID).append(SPILIT).append(id);
        return sb.toString();
    }

    @Override
    public List<Book> findBookList() {
        return bookDao.queryAll();
    }

    @Override
    public Book findBookById(Long id) {
        Book book = null;
        String key = idKey(id, BOOK_KEY);
        if (redisUtil.exists(key)) { //如果缓存中存在此key
            return (Book) redisUtil.get(key); //从缓存中查询此key对应的value
        }
        book = bookDao.query(id);
        if (book != null) {
            redisUtil.set(key, book, EXPIRE_TIME);
        }
        return book;
    }

    @Override
    public void delBook(Long id) {
        String key = idKey(id, BOOK_KEY);
        if (redisUtil.exists(key)) { //如果缓存中存在此key
            redisUtil.remove(key); //先删除缓存
        }
        bookDao.delete(id); //再删除数据库
    }

    @Override
    public void updateBook(Book book) {
        String key = idKey(book.getId(), BOOK_KEY);
        redisUtil.set(key, book, EXPIRE_TIME);//先更新缓存
        bookDao.update(book); //再更新数据库
    }

    @Override
    public void syncFile(List<SyncUserVO> list, Long bookId) {
        //文件导入的时候就提示用户成功，然后在后台开个线程去跑
        if (list != null && !list.isEmpty()) {
            new Thread(new SyncThread(list, bookId)).start();
        }
    }
}

/**
 * Revision history
 * -------------------------------------------------------------------------
 * 
 * Date Author Note
 * -------------------------------------------------------------------------
 * 2017年9月7日 wanghb create
 */
